//
//  HomeViewController.m
//  Wujin
//
//  Created by cz on 2016/12/7.
//  Copyright © 2016年 dong. All rights reserved.
//

#define margin 10
#define sliderShowHeight 150

#import "HomeViewController.h"
#import "MJRefresh.h"
#import "SliderShowView.h"
#import "GoodCollectionViewCell.h"
#import "TTLoopView.h"
#import "AdvModel.h"
#import "AdvertViewController.h"
#import "SearchView.h"
#import "SearchGoodsViewController.h"
#import "GoodsDetail.h"

@interface HomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,UITextFieldDelegate,SearchViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *goodList;
@property (nonatomic,strong) AdvModel *advModel;
/**
 广告页
 */
@property (nonatomic,strong) NSMutableArray *advImgUrl;
@property (nonatomic,strong) SearchView *searchBar;

@end

@implementation HomeViewController

static NSString * const goodResueId = @"goodCell";
static NSString * const sliderId = @"sliderCell";

- (NSMutableArray *)advImgUrl {
    if (!_advImgUrl) {
        _advImgUrl = [NSMutableArray array];
    }
    return _advImgUrl;
}

- (NSMutableArray *)goodList {
    if (!_goodList) {
        _goodList = [NSMutableArray array];
    }
    return _goodList;
}

/**
 懒加载collectionView
 */
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(100, 100);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, SCREENBOUNDS.width, SCREENBOUNDS.height) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        
        //注册cell
        [self.collectionView registerNib:[UINib nibWithNibName:@"GoodCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:goodResueId];
        [self.collectionView registerClass:[UICollectionReusableView class]  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:sliderId];
    }
    return _collectionView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //设置UI
    [self setupUI];
}

- (void)setupUI {
    
    //设置collectionView
    [self.view addSubview:self.collectionView];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    //设置导航条按钮
    [self setupNavBarItem];
    //设置刷新控件
    [self setupRefreshControl];
    //自动刷新控件
    [self.collectionView.mj_header beginRefreshing];
}


/**
  设置导航条按钮
 */
- (void)setupNavBarItem {
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    searchBtn.frame = CGRectMake(0, 0, 26, 26);
    
    [searchBtn addTarget:self action:@selector(setUpSearchBar) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
}

//设置搜索条
- (void)setUpSearchBar{
    
    SearchView *seachBar = [SearchView setupSearchView];
    seachBar.delegate = self;
    seachBar.searchTextFiled.delegate = self;
    _searchBar = seachBar;
    self.navigationItem.titleView = seachBar;
}

//键盘上的确定按钮的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self handleSearchBar];
    
    return YES;
}


/**
处理搜索条，进行相应的功能
 */
- (void)handleSearchBar {
    if ([_searchBar.searchTextFiled.text isEqualToString:@""]) {
        
        DLog(@"搜索结果不能为空");
        [MRHud show];
        [MRHud dismissWithFailure:@"请输入商品名"];
        
    }else{
        DLog(@"%@",_searchBar.searchTextFiled.text);
        SearchGoodsViewController *searchVc = [[SearchGoodsViewController alloc] init];
        searchVc.keyword = self.searchBar.searchTextFiled.text;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchVc];
        [self presentViewController:nav animated:YES completion:nil];
    }
}

//搜索框的代理方法
- (void)searchButtonDidClicked {
    [self handleSearchBar];
}

- (void)cancelButtonDidClicked {
    //设置标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"首页";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [titleLabel sizeToFit];
    self.navigationItem.titleView = titleLabel;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self cancelButtonDidClicked];
}

//view已经消失，移除搜索框
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.searchBar removeFromSuperview];
}

#pragma mark -- collectionView的代理与数据源方法
//组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}
//行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.goodList.count;
}

//设置每个cell的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
    
}

//设置每个item的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat width = SCREENBOUNDS.width * 0.5;
    
    return CGSizeMake(width, width * 1.3);
}

//设置头视图的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (section == 0){
        return CGSizeMake(SCREENBOUNDS.width,190);
    }
    return CGSizeMake(0, 0);
}


/**
   设置collectionView的头部视图
 */
- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:sliderId forIndexPath:indexPath];
        //添加图片轮播器
        [self setUpSliderShow:view];
        //设置提示view
        [view addSubview:[self setupTipLabel]];
        
        return view;
    }
    return nil;
}

//设置提示view
- (UILabel *)setupTipLabel {
    
    //添加label
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(margin, sliderShowHeight + 10, SCREENBOUNDS.width, 20)];
    tipLabel.text = @"全部产品";
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.textColor = rgb(253, 199, 30);
    
    return tipLabel;
}

/**
   设置collectionViewcell
 */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        
    
    GoodCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:goodResueId forIndexPath:indexPath];
    cell.goodsList = self.goodList[indexPath.row];
    return cell;
}

/**
 点击cell调用,跳转到商品详情
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    DLog(@"%ld",(long)indexPath.row);
    GoodsDetail *detail = [UIViewController storyboardWithName:@"Home" storyboardID:@"goodsdetail"];
    GoodsModel *model = _goodList[indexPath.row];
    detail.goodsID = model.gds_id;
    [self pushViewController:detail];
    
}

//一开始滚动，就退出键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.searchBar endEditing:YES];
}

/**
 设置图片轮播器
 */
- (void)setUpSliderShow:(UICollectionReusableView *) view{
    
    NSMutableDictionary *dict = nil;
    NSString *url = F(@"%@Public/getAdv", BASEURL);
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([responseObject[@"flag"] intValue] == 1) {
                NSDictionary *dict = responseObject[@"data"];
                NSArray *array = dict[@"map"];
                self.advImgUrl = nil;
                self.advModel = nil;
                for (NSDictionary *advDict in array) {
                    AdvModel *advModel = [AdvModel advModelWithDict:advDict];
                    _advModel = advModel;
                    [self.advImgUrl addObject:advModel.img_url];
                }
            }else{
                DLog(@"网络请求失败 %@",error);
            }
        }
    }];
    
    TTLoopView *sliderView = [TTLoopView LoopViewWithURLs:self.advImgUrl titles:nil didSelected:^(NSInteger itemIndex) {
        DLog(@"第%zd张,%@",itemIndex,self.advModel.jump_url);
        
        [self jumpToAdvertView:self.advModel.jump_url];
    }];
    sliderView.placeHolderImage = [UIImage imageNamed:@"bg_1"];
    sliderView.timerInterval = 4.0;
    sliderView.frame = CGRectMake(0, 0, SCREENBOUNDS.width, sliderShowHeight);
    [view addSubview:sliderView];
}

/**
 传入网址跳转到广告页面
 */
- (void)jumpToAdvertView:(NSString *) urlStr {
    
    if (urlStr.length == 0 || ![urlStr hasPrefix:@"http://"]) {
        return;
    }    
    AdvertViewController *adVc = [[AdvertViewController alloc] init];
    adVc.urlStr = urlStr;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:adVc];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

/**
    设置刷新控件
 */
- (void)setupRefreshControl {
    //添加下拉刷新控件
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewShopData)];
    //添加上拉刷新控件
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreShopData)];
}

/**
   加载新的商品数据
 */
- (void)loadNewShopData {
    //一下拉，就停止上拉刷新
    [self.collectionView.mj_footer endRefreshing];
    //只要一上拉刷新，就把下拉刷新请求的起始页数重置
    i = 2;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"page"] = @(1);
    dict[@"limit"] = @10;
    NSString *url = F(@"%@Index/goodsList", BASEURL);
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([responseObject[@"flag"] intValue] == 1) {
                NSDictionary *dict = responseObject[@"data"];
                NSArray *array = dict[@"goods"];
                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, array.count)];
                NSMutableArray *tempA = [NSMutableArray array];
                self.goodList = nil;
                for (NSDictionary *goodsDict in array) {
                    GoodsModel *goodsList = [GoodsModel yy_modelWithDictionary:goodsDict];
                    [tempA addObject:goodsList];
                }
                [self.goodList insertObjects:tempA atIndexes:indexSet];
                [self.collectionView reloadData];
                //停止刷新
                [self.collectionView.mj_header endRefreshing];
            }else{
                DLog(@"没有请求到数据");
            }
        }
    }];
}

/**
   加载更多商品数据
 */

//下拉加载更多的起始页数
static NSInteger i = 2;
//下拉刷新的上限
static NSInteger maxI = 10;

- (void)loadMoreShopData {
    
    //一上拉，就停止下拉刷新
    [self.collectionView.mj_header endRefreshing];
    
    if (i > maxI) {//超过10次，就不再加载了
        
        [self.collectionView.mj_footer endRefreshing];
        [MRHud show];
        [MRHud dismissWithFailure:@"没有更多商品了"];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"limit"] = @10;
    dict[@"page"] = F(@"%ld", (long)i);    
    
    NSString *url = F(@"%@Index/goodsList", BASEURL);
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        NSDictionary *dict = responseObject[@"data"];
        if ([responseObject[@"flag"] intValue] == 1 && dict.count != 0) {
            
            i++;
            
            NSArray *array = dict[@"goods"];
            NSMutableArray *tempA = [NSMutableArray array];
            for (NSDictionary *goodsDict in array) {
                GoodsModel *goodsList = [GoodsModel yy_modelWithDictionary:goodsDict];
                [tempA addObject:goodsList];
            }
            [self.goodList addObjectsFromArray:tempA];
            
            [self.collectionView reloadData];
            //停止刷新
            [self.collectionView.mj_footer endRefreshing];
        }else{
            DLog(@"没有请求到数据");
            
            [self.collectionView.mj_footer endRefreshing];
            
            [MRHud show];
            [MRHud dismissWithFailure:@"没有更多商品了"];
            
        }
    }];
}

@end
